package com.caigp.cookbook2.activity;

import androidx.annotation.NonNull;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.caigp.cookbook2.R;
import com.caigp.cookbook2.base.BaseActivity;
import com.caigp.cookbook2.bean.CookBook;
import com.caigp.cookbook2.bean.Favorite;
import com.caigp.cookbook2.util.AppUtil;
import com.caigp.cookbook2.util.HttpClient;
import com.caigp.cookbook2.util.JsonUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.makeramen.roundedimageview.RoundedImageView;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnTouch;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DetailActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = DetailActivity.class.getSimpleName();

    private CookBook cookBook;

    private int id;

    private String name;

    float downY;

    float downX;

    @BindView(R.id.detail_layout)
    LinearLayout detailLayout;

    @BindView(R.id.scroll_view)
    ScrollView scrollView;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String result = (String) msg.obj;
                    JsonObject jsonObject = JsonParser.parseString(result).getAsJsonObject();
                    int status = jsonObject.get("status").getAsInt();
                    if (status == 0) {
                        JsonObject resultJsonObject = jsonObject.get("result").getAsJsonObject();
                        Gson gson = JsonUtil.getInstance();
                        cookBook = gson.fromJson(resultJsonObject, CookBook.class);
                        showDetailLayout();
                    } else if (status == 205) {
                        //没有信息

                    }
                    break;
                case 1:

                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        ButterKnife.bind(this);
        getCookBook();
        if (cookBook != null) {
            showDetailLayout();
            name = cookBook.getName();
        } else {
            requestData();
        }
        setActionBarTitle(name);
    }

    @OnTouch(R.id.scroll_view)
    public boolean onTouch(MotionEvent e) {
        switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downY = e.getY();
                downX = e.getX();
                break;
            case MotionEvent.ACTION_UP:
                float upY = e.getY();
                float upX = e.getX();

                if (upY > downY ? upY - downY < 100: downY - upY < 100 && upX > downX ? upX - downX > 300: downX - upX > 300) {
                    this.finish();
                    return true;
                }
                break;
        }
        return false;
    }

    @Override
    protected boolean showHomeAsUp() {
        return true;
    }

    private void requestData() {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", String.valueOf(id))
                .add("appkey", AppUtil.appkey)
                .build();
        HttpClient.sendPost(AppUtil.detail, requestBody, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                handler.sendEmptyMessage(1);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int code = response.code();
                if (code == 200) {
                    String body = response.body().string();
                    Message message = handler.obtainMessage();
                    message.obj = body;
                    message.what = 0;
                    handler.sendMessage(message);
                }
            }
        });
    }

    /**
     * 将布局显示出来
     */
    @SuppressLint("SetTextI18n")
    private void showDetailLayout() {
        ViewGroup.LayoutParams roundedImageParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 600);
        RoundedImageView roundedImageView = new RoundedImageView(this);
        roundedImageView.setLayoutParams(roundedImageParams);
        roundedImageView.setScaleType(ImageView.ScaleType.CENTER);
        roundedImageView.setCornerRadius(20);
        Glide.with(this).load(cookBook.getPic()).placeholder(R.drawable.load).error(R.drawable.error).into(roundedImageView);
        detailLayout.addView(roundedImageView);

        Button button = new Button(this);
        button.setId(0);
        button.setOnClickListener(this);
        button.setTypeface(Typeface.DEFAULT_BOLD);
        button.setText("收藏");
        //button.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        detailLayout.addView(button);

        LinearLayout.LayoutParams contentParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        contentParams.topMargin = 10;
        contentParams.bottomMargin = 10;
        TextView content = new TextView(this);
        content.setTextSize(16);
        content.setText(Html.fromHtml(cookBook.getContent()));
        content.setLayoutParams(contentParams);
        detailLayout.addView(content);

        TextView material = new TextView(this);
        material.setText("用料");
        material.setTextSize(20);
        material.setTextColor(Color.BLACK);
        material.setTypeface(Typeface.DEFAULT_BOLD);
        material.setGravity(Gravity.CENTER);
        detailLayout.addView(material);

        List<CookBook.Material> materialList = cookBook.getMaterial();
        LinearLayout.LayoutParams materialTvParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        materialTvParams.weight = 1;
        materialTvParams.topMargin = 10;
        materialTvParams.bottomMargin = 10;
        for (int i = 0; i < materialList.size(); i++) {
            LinearLayout linearLayout = new LinearLayout(this);
            TextView tv1 = new TextView(this);
            TextView tv2 = new TextView(this);
            tv1.setText(materialList.get(i).getMname());
            tv2.setText(materialList.get(i).getAmount());
            tv1.setLayoutParams(materialTvParams);
            tv2.setLayoutParams(materialTvParams);
            tv1.setGravity(Gravity.CENTER);
            tv2.setGravity(Gravity.CENTER);
            linearLayout.addView(tv1);
            linearLayout.addView(tv2);
            detailLayout.addView(linearLayout);
        }

        TextView process = new TextView(this);
        process.setText("做法");
        process.setTextSize(20);
        process.setTextColor(Color.BLACK);
        process.setTypeface(Typeface.DEFAULT_BOLD);
        process.setGravity(Gravity.CENTER);
        detailLayout.addView(process);

        List<CookBook.Process> processList = cookBook.getProcess();
        LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 600);
        imageParams.bottomMargin = 30;
        imageParams.topMargin = 30;
        for (int i = 0; i < processList.size(); i++) {
            TextView tv = new TextView(this);
            tv.setText(Html.fromHtml(i + 1 + "、" + processList.get(i).getPcontent()));
            RoundedImageView image = new RoundedImageView(this);
            image.setLayoutParams(imageParams);
            image.setScaleType(ImageView.ScaleType.CENTER);
            image.setCornerRadius(20);
            Glide.with(this).load(processList.get(i).getPic()).placeholder(R.drawable.load).error(R.drawable.error).into(image);
            detailLayout.addView(tv);
            detailLayout.addView(image);
        }
    }

    private void getCookBook() {
        Intent intent = getIntent();
        cookBook = intent.getParcelableExtra("cookBook");
        id = intent.getIntExtra("id", 0);
        name = intent.getStringExtra("name");
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == 0) {
            List<Favorite> favoriteList = findFavorite();
            for (int i = 0; i < favoriteList.size(); i++) {
                Favorite favorite = favoriteList.get(i);
                int iid = favorite.getIid();
                if (iid == cookBook.getId()) {
                    Toast.makeText(this, "你已经收藏过了", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            Favorite favorite = new Favorite();
            favorite.setIid(cookBook.getId());
            favorite.setName(cookBook.getName());
            favorite.setPic(cookBook.getPic());
            boolean result = favorite.save();
            if (result) {
                Toast.makeText(this, "收藏成功", Toast.LENGTH_LONG).show();
            }
        }
    }
}
